public with sharing class ManualSubmissionForm_AC {
                
    public Case tempCase;
    
    //Boolean values used to render the page blocks or forms in the page
    public boolean MyWest = false;
    public boolean West = false;
    public boolean Form{get;set;}
    public boolean Submit_Successful{get;set;}
    
    // Values used to pre-populate or retrieve Data
    public String Student_ID{get; set;}    
    public String First_Name{get; set;}
    public String Last_Name{get; set;}
    public String Email{get; set;}

    public String State{get; set;}

    Public String FirstNameError{get; set;}
    //public String Renderid{get; set;}
    
    public String xml_Content = '';
    public String createdCaseID = '';
    public String source = '';
//    public String Case_Number{get; set;}
        
    public String ErrorMsg{get; set;}
    public Boolean DisplayPageMessage{get; set;}
    public Boolean isStateError{get; set;}
        
    public RecordType caseRecordType = [select Id from RecordType where Name = 'CMS'];
    
    public String[] secureIPList = new String[] {'https://prod.campuscruiser.com','216.35.68.45','216.35.68.59','204.17.16.49','68.106.3.85','216.35.68.38','216.35.68.39','216.35.68.40','216.35.68.41','216.35.68.42', '216.35.68.43','216.35.68.44','216.35.68.46','216.35.68.47','216.35.68.48','216.35.68.49','216.35.68.50','216.35.68.51','216.35.68.52','216.35.68.53','216.35.68.54','216.35.68.55','216.35.68.56','216.35.68.57','216.35.68.58'};
    private Boolean isSecure = false;
        
    // the Case record you are adding values to
  public Case caseCon {
    get {
      if (caseCon == null){
        caseCon = new Case();
        caseCon.Account = new Account();
        }
      return caseCon;
    }
    set;
  }
  
  public String[] StateList = new String[] {'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' };
  
  public List<SelectOption> getstates(){  
        List<SelectOption> picklistValues = new List<SelectOption>();
        picklistValues.add(new SelectOption('','Select State'));
        for (Integer i=0;i<StateList.size();i++)
          {
        picklistValues.add(new SelectOption(StateList[i],StateList[i]));
        }
        return picklistValues;        
  }
  
  public String wasWestStudent{get; set;}
  
  public String[] wasWestStudentList = new String[] {'Yes', 'No'};
  
  public List<SelectOption> getWestStudent(){  
        List<SelectOption> picklistValues = new List<SelectOption>();

        for (Integer i=0;i<wasWestStudentList.size();i++)
          {
        picklistValues.add(new SelectOption(wasWestStudentList[i],wasWestStudentList[i]));
        }
        return picklistValues;        
  }
  
  public String campus{get; set;}
  
  public List<SelectOption> getcampusLocations(){  
        List<SelectOption> picklistValues = new List<SelectOption>();
        List<Campus__c> campusList = [Select Name from Campus__c where RecordType.Name = 'West - Campus' ];        
        for (Integer i=0;i<campusList.size();i++)
          {
        picklistValues.add(new SelectOption(campusList[i].Name,campusList[i].Name));
        
        }
        if(!picklistValues.isEmpty()){
            picklistValues = sortSelectOptions(picklistValues);        
            picklistValues.add(0, new SelectOption('','Select your Campus'));
        }
        else
            picklistValues.add(new SelectOption('','Select your Campus'));
        return picklistValues;      
  }
  
  
  // Sorting Picklist Values
  public List<SelectOption> sortSelectOptions(List<SelectOption> sortSelectOptionList) {
    for (Integer i =0; i < sortSelectOptionList.size(); i++) {
        for (Integer j = i; j > 0; j--) {
            if (sortSelectOptionList[j-1].getLabel() > sortSelectOptionList[j].getLabel()){
                SelectOption temp = sortSelectOptionList[j];
                sortSelectOptionList[j] = sortSelectOptionList[j-1];
                sortSelectOptionList[j-1] = temp;
            }
        }
    }
    return sortSelectOptionList;
  }
  
  public String program{get; set;}
  
  public List<SelectOption> getprogramDetails(){  
        List<SelectOption> picklistValues = new List<SelectOption>();
        List<Program__c> programList = [Select Name from program__c where RecordType.Name = 'West - Program' ];
        
        for (Integer j=0;j<programList.size();j++){
            picklistValues.add(new SelectOption(programList[j].Name,programList[j].Name));
        }
        if(!picklistValues.isEmpty()){
            picklistValues = sortSelectOptions(picklistValues);
            picklistValues.add(0, new SelectOption('','Select a Program'));
        }        
        return picklistValues;        
  }
  /*
  public String catalog{get; set;}
  
  public List<SelectOption> getcatalogNumbers(){  
        List<SelectOption> picklistValues = new List<SelectOption>();       
        picklistValues.add(new SelectOption('','Select'));
                
        for ( Catalog__c catalogs : [Select Name from Catalog__c]){
            picklistValues.add(new SelectOption(catalogs.Name,catalogs.Name));
        }
        return picklistValues;        
  }
  */  
    // Constructor
    public ManualSubmissionForm_AC(ApexPages.StandardController stdController) {
    
        CaseCon = (Case)stdController.getRecord();
        CaseCon.Account = new Account();
        
        // Display The Form and Hide Post Submit Content
        Form = true;
        Submit_Successful = false;
        isSecure = false;
        isStateError = false;
               
        // Read the parameters and get them into readable format 
        for (String thisKey : ApexPages.currentPage().getParameters().keySet()){
            xml_Content += thisKey + ' :: ' + ApexPages.currentPage().getParameters().get(thisKey) + '\n';        
        }       
        
        
        // Encloding XML content        
        xml_Content = EncodingUtil.urlDecode(xml_Content, 'UTF-8');
        
        // parsing the Name tag from the XML
        if( xml_Content.indexof('<NAME>') > 0)
        source = xml_Content.substring(xml_Content.indexof('<NAME>')+6, xml_Content.indexof('</NAME>'));                   
        /*
        // checking if the Origin is secure
        for(String str: secureIPList){
            if( str.equals(ApexPages.currentPage().getHeaders().get('Origin'))){            
                isSecure = true;
                break;
            }
        }
        */        
        // check if it is MyWest and Secure
        if( source == 'MyWest'){
            
            //displaying the MyWest page block
            MyWest = true;
            West = false;
            
            // parsing xml using subString  method
            Student_ID = xml_Content.substring(xml_Content.indexof('<ID>')+4, xml_Content.indexof('</ID>'));
            First_Name = xml_Content.substring(xml_Content.indexof('<GIVEN>')+7, xml_Content.indexof('</GIVEN>'));
            Last_Name = xml_Content.substring(xml_Content.indexof('<FAMILY>')+8, xml_Content.indexof('</FAMILY>'));
            Email = xml_Content.substring(xml_Content.indexof('<EMAIL>')+7, xml_Content.indexof('</EMAIL>'));
            
            // Assignng values
            CaseCon.Account.External_ID_2__c = Student_ID ; 
            CaseCon.Account.PersonEmail = Email;
            CaseCon.Account.FirstName = First_Name;
            CaseCon.Account.LastName = Last_Name;            
            //CaseCon.Description = '';
                    
        }
        else // display west page with text fields 
        {
            West = true;
            MyWest = false; 
        }
        
        // Adding 3 Attachments Page Block
        newAttachments=new List<Attachment>{new Attachment()};
        for(integer i=1;i<3;i++)        
        newAttachments.add(new Attachment());
        
    }
        
    /******************* Attachment Section Start **************************/
    
    // list of existing attachments - populated on demand
    //public List<Attachment> attachments;
    
    // list of new attachments to add
    public List<Attachment> newAttachments {get; set;}
    
    // the number of new attachments to add to the list when the user clicks 'Add More'
    public static final Integer NUM_ATTACHMENTS_TO_ADD=5;
    
    // Add more attachments action method
    public void addMore(){
        // append NUM_ATTACHMENTS_TO_ADD to the new attachments list
        for (Integer idx=0; idx<NUM_ATTACHMENTS_TO_ADD; idx++){
            newAttachments.add(new Attachment());
        }
    }    
    /******************** Attachment Section Completed ************************/
    
        
    public boolean getMyWest(){
        return this.MyWest;
    }
    
    public boolean getWest(){
        return this.West;
    }
    
    
    // Submit functionality
    public PageReference Submit(){
        isStateError = false;
        boolean insertAttach  = false;
        TempCase = new Case();
    
        TempCase.Status = 'New';
        TempCase.Subject = '';
        TempCase.Origin = 'Web';
        TempCase.Description = 'Student ID: '+ CaseCon.Account.External_ID_2__c + '\n' + 'Student Name: '+ CaseCon.Account.FirstName + ' ' + CaseCon.Account.LastName + '\n' + 'Student Email: ' + CaseCon.Account.PersonEmail + '\n' + 'Student Date of Birth: ' + CaseCon.Account.PersonBirthDate.month() + '/' + CaseCon.Account.PersonBirthDate.day() + '/' + CaseCon.Account.PersonBirthDate.year() + '\nAddress : ' + CaseCon.Account.PersonMailingStreet + ', ' + CaseCon.Account.PersonMailingCity + ', ' + State + ', ' + CaseCon.Account.PersonMailingPostalCode + '\nHome Phone: ' + CaseCon.Account.PersonHomePhone + '\nWork Phone: ' + CaseCon.Account.Work_Phone__c + '\nMessage Phone: '  + CaseCon.Account.Message_Phone__c + '\nCampus: ' + campus + '\nProgram: ' + program; // + '\nCatalog: ' + catalog;
        
        if( West){
            TempCase.Description += '\n Source:West Website \n Has Attended West: ';
            if( wasWestStudent.equals('Yes'))
                TempCase.Description += 'Yes';
            else
                TempCase.Description += 'No';
        }
        
        TempCase.Description += '\n\n' + 'Issue: \n\n' + CaseCon.Description; 
        TempCase.RecordTypeId = CaseRecordType.Id;
    
        try{
            /*
            FirstNameError='';
            if( CaseCon.Account.PersonHomePhone == NULL)
            {
                FirstNameError='a'; return null;
            }
            if( State == '' || campus == '')
             {   CaseCon.Account.Message_Phone__c.adderror('value'); return null;}
            
             if(State.equals('Alabama')){             
              isStateError = true;
              CaseCon.Description = state;
             }
             */    
            if( TempCase.Description != NULL){
            
                Database.saveResult dsr = Database.insert(TempCase);
                createdCaseID = dsr.getId();
                insertAttach = true;
            } 
            if(insertAttach){
                transient List<Attachment> AttachmentstoInsert=new List<Attachment>();
                for (Attachment newAtt : newAttachments){
                    if (newAtt.Body!=null){
                        newAtt.parentId=TempCase.id;
                        AttachmentstoInsert.add(newAtt);
                    }
                }
                insert AttachmentstoInsert;                
               
            }
            Form = false;
            Submit_Successful = true;
        }
        catch(System.DMLException e) {
            
        }
        catch(System.Exception e){

        }
        
        finally{        
            // Make body null for the attachments to avoid exceeding view state limit                
            for (Attachment newAtt : newAttachments){
                newAtt.Body = NULL;
            }        
        }
        return null;
    }
}